<?php


namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\model\Currency;
use app\api\model\UserAssetsAuth;
use app\api\model\UserAuthLike;
use app\api\model\UserAuthOrder;
use app\api\model\UserAuthReport;
use app\api\model\UserAuthShare;
use app\api\model\UserEducationAuth;
use app\api\model\UserIncomeAuth;
use app\api\model\UserJobAuth;
use app\api\model\UserPrivacy;
use app\api\model\UserPrivacyList;
use app\api\model\UserRealAuth;
use app\api\service\Token as TokenService;
use app\api\model\System as SystemModel;
use app\api\model\UserAuth as UserAuthModel;
use app\api\model\UserAuthZan;
use app\api\validate\CheckContent;
use app\lib\exception\ParameterException;
use app\api\model\User as UserModel;
use think\Db;


class UserAuth extends BaseController
{
    protected $beforeActionList = [
        'checkExclusiveScope' => ['only' => 'getRecommendDataList,getDataList']
    ];

    /**
     * 创建订单
     */
    public function createOrder()
    {
        $openid = TokenService::getCurrentTokenVar("openid");
        $info = UserAuthModel::where('openid',$openid)->find();
        $order = UserAuthOrder::where('openid',$openid)
            ->where('status',1)
            ->find();
        $system = SystemModel::get(1);
        if($order) {
            $order->price = $system['user_auth_price'];
            $order->user_auth_msg = json_encode($info);
            $order->save();
            return UserAuthOrder::where('openid',$openid)
                ->find();
        } else {
            $mode = UserAuthOrder::create([
                'openid' => $openid,
                'price' => $system['user_auth_price'],
                'user_auth_msg' => json_encode($info),
            ]);
            $mode->out_trade_no = '5t2021'.$mode->id;
            $mode->save();
            return UserAuthOrder::where('openid',$openid)
                ->find();
        }
    }

    /**
     * 获取用户上墙推荐首页信息列表
     */
    public function getRecommendDataList()
    {
        return UserAuthModel::where('recommend',1)
            ->where('status',2)
            ->where('state',2)
            ->order('order_sort desc')
            ->with('imgs.img')
            ->select()
            ->toArray();
    }

    /**
     * 获取用户上墙信息列表
     */
    public function getDataList($page,$limit,$gender,$sort_type,$sort_type_status)
    {
        $where = [];
        if($gender) {
            $where[] = ['gender','eq',$gender];
        }
        if($sort_type == 1) {
            $orderSort = 'order_sort';
            $sc = ' desc';
        } elseif($sort_type == 2) {
            $orderSort = 'hot';
            $sc = ' '.$sort_type_status;
        } elseif($sort_type == 3) {
            $orderSort = 'update_time';
            $sc = ' '.$sort_type_status;
        }
        $query = UserAuthModel::with('imgs.img')->where($where)->order($orderSort.$sc);
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取用户信息上墙操作
     */
    public function getUserAuthRecommendList()
    {
        $where = [];
        $query = UserAuthModel::with('imgs.img')->where($where)->order('hot desc');
        $result = $query->select()->toArray();
        return $result;
    }

    /**
     * 获取用户信息
     */
    public function getDataInfo($id)
    {
        $openid = TokenService::getCurrentTokenVar('openid');
        $user = UserModel::where('openid',$openid)->find();
        UserAuthModel::where('id',$id)->setInc('hot',1);
        $info = UserAuthModel::with('imgs.img')->where('id',$id)->find();
        $info['zan'] = UserAuthZan::where('user_auth_id',$info['id'])
            ->where('openid',$openid)
            ->find();
        $info['like'] = UserAuthLike::where('user_auth_id',$info['id'])
            ->where('openid',$openid)
            ->find();
        $info['zan_num'] = UserAuthZan::where('user_auth_id',$info['id'])->count();
        $info['user'] = UserModel::where('openid',$info['openid'])->find();
        // 实名认证
        $info['auth_real'] = UserRealAuth::where('openid',$info['openid'])
            ->with('justImg,backImg')->find();
        // 手机认证
        $info['auth_phone'] = $user['phone'];
        // 学历认证
        $info['auth_education'] = UserEducationAuth::where('openid',$info['openid'])
            ->find();
        // 工作证明
        $info['auth_job'] = UserJobAuth::where('openid',$info['openid'])
            ->with('jobImg')->find();
        // 收入证明
        $info['auth_income'] = UserIncomeAuth::where('openid',$info['openid'])
            ->with('incomeImg')->find();
        // 资产证明
        $info['auth_assets'] = UserAssetsAuth::where('openid',$info['openid'])
            ->with('assetsImg')->find();
        // 用户隐私设置信息
        $info['user_privacy'] = UserPrivacy::where('openid',$info['openid'])
            ->find();
        // 当前用户是否可查看
        $info['user_privacy_list'] = UserPrivacyList::where('y_openid',$openid)
            ->where('b_openid',$info['openid'])
            ->find();
        return $info;
    }

    /**
     * 点赞
     */
    public function addZan($user_auth_id)
    {
        $openid = TokenService::getCurrentTokenVar('openid');
        $info = UserAuthZan::where('openid',$openid)
            ->where('user_auth_id',$user_auth_id)->find();
        if($info) {
            throw new ParameterException([
                'msg' => [
                    'user_auth' => '已经点赞'
                ]
            ]);
        }
        $date = date('Y-m-d');
        UserAuthZan::create([
            'openid'=> $openid,
            'user_auth_id' => $user_auth_id,
            'date' => $date
        ]);
        $info_one = UserAuthZan::where('openid',$openid)
            ->where('date',$date)->find();
        if(!$info_one) {
            $end_time = time() + 604800;
            Currency::create([
                'openid' => $openid,
                'number' => 10,
                'type' => 1,
                'status' => 5,
                'end_time' => $end_time,
                'day_date' => $date,
                'min_number' => 10,
                'msg_json' => json_encode($info)
            ]);
        }
        return writeJson(201, [], '点赞成功！');
    }

    /**
     * 添加分享
     */
    public function addShare($user_auth_id)
    {
        $openid = TokenService::getCurrentTokenVar('openid');
        $date = date('Y-m-d');
        UserAuthShare::create([
            'openid'=> $openid,
            'user_auth_id' => $user_auth_id,
            'date' => $date
        ]);
        $info_one = UserAuthShare::where('openid',$openid)
            ->where('date',$date)->find();
        if(!$info_one) {
            $end_time = time() + 604800;
            Currency::create([
                'openid' => $openid,
                'number' => 10,
                'type' => 1,
                'status' => 6,
                'end_time' => $end_time,
                'day_date' => $date,
                'min_number' => 10,
            ]);
        }
        return writeJson(201, [], '分享成功！');
    }

    /**
     * 喜欢列表
     */
    public function getUserAuthLikeList()
    {
        $openid = TokenService::getCurrentTokenVar('openid');
        $one = UserAuthLike::where('openid',$openid)
            ->with('userAuth.imgs.img')->select()->toArray();
        $two = UserAuthLike::where('user_auth_openid',$openid)
            ->with('userAuth.imgs.img')->select()->toArray();
        return [
            'one' => $one,
            'two' => $two,
        ];
    }

    /**
     * 喜欢操作
     */
    public function addLike($user_auth_id)
    {
        $openid = TokenService::getCurrentTokenVar('openid');
        $info = UserAuthLike::where('openid',$openid)
            ->where('user_auth_id',$user_auth_id)
            ->find();
        if(!$info) {
            $user_auth = UserAuthModel::where('id',$user_auth_id)
                ->find();
            UserAuthLike::create([
                'openid'=> $openid,
                'user_auth_id' => $user_auth_id,
                'user_auth_openid' => $user_auth['openid']
            ]);
            if(UserAuthLike::where('openid',$user_auth['openid'])->where('user_auth_openid',$openid)->find()) {
                $type = 2;
            } else {
                $type = 1;
            }
        } else {
            UserAuthLike::destroy($info['id']);
            $type = 1;
        }
        return writeJson(201, ['type'=>$type], '操作成功！');
    }


    /**
     * 提交投诉
     */
    public function addReport($user_auth_id,$fileList,$type,$content)
    {
        (new CheckContent())->goCheck();
        $openid = TokenService::getCurrentTokenVar("openid");
        $info = UserAuthModel::where('id',$user_auth_id)
            ->with('imgs.img')->find();
        if(!$info) {
            throw new ParameterException([
                'msg' => [
                    'user_auth' => '请重新选择信息'
                ]
            ]);
        }
        Db::startTrans();
        try{
            $mode = UserAuthReport::create([
                'user_auth_id' => $user_auth_id,
                'type' => $type,
                'content' => $content,
                'openid' => $openid,
                'json_msg' => json_encode($info)
            ]);
            $img_data = [];
            foreach ($fileList as $k=>$v){
                $img_data[$k] = ['img_id'=>$v['img_id']];
            }
            $mode->imgs()->saveAll($img_data);
            Db::commit();
            return writeJson(201, [], '提交成功,感谢您的监督！');
        }catch (Exception $ex){
            Db::rollback();
            throw new ParameterException([
                'msg' => [
                    'gr' => '提交失败!'
                ]
            ]);
        }
    }
}